<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-container">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="queryParams.realName" placeholder="请输入姓名" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="用户状态" clearable style="width: 200px">
            <el-option label="正常" value="1" />
            <el-option label="待审核" value="2" />
            <el-option label="已认证" value="3" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" :icon="Plus" @click="handleAdd">
          新增用户
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-button :icon="Refresh" @click="handleRefresh">刷新</el-button>
      </div>
    </div>

    <!-- 用户表格 -->
    <el-table v-loading="loading" :data="userList" border stripe>
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="昵称" prop="nickname" min-width="120" align="center" />
      <el-table-column label="真实姓名" prop="realName" min-width="120" align="center" />
      <el-table-column label="手机号" prop="phone" min-width="130" align="center" />
      <el-table-column label="密码" prop="password" min-width="130" align="center" />
      <el-table-column label="身份证号" prop="idCard" min-width="180" align="center">
        <template #default="{ row }">
          <span v-if="row.idCard">{{ row.idCard.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2') }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" min-width="100" align="center">
        <template #default="{ row }">
          {{ userStatus[row.status] }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="created_at" width="180" align="center">
        <template #default="{ row }">
          {{ row.created_at }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize" :total="total"
        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" @size-change="handleQuery"
        @current-change="handleQuery" />
    </div>

    <!-- 用户表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" @close="handleDialogClose">
      <el-form ref="userFormRef" :model="userForm" :rules="userRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="昵称">
              <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号码" prop="idCard">
              <el-input v-model="userForm.idCard" placeholder="请输入身份证号码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="!isEdit">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="userForm.confirmPassword" type="password" placeholder="请确认密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="userForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Edit,
  Download,
} from "@element-plus/icons-vue";
import UserAPI from "@/api/user";

defineOptions({
  name: "User",
});

// 响应式数据
const loading = ref(false);
const submitLoading = ref(false);
const dialogVisible = ref(false);
const isEdit = ref(false);
const total = ref(0);
const userList = ref<UserItem[]>([]);
const multipleSelection = ref<UserItem[]>([]);
const userStatus: any = ref({
  1: "正常",
  2: "待审核",
  3: "已认证",
  0: "禁用",
})
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  realName: "",
  phone: "",
  status: "",
});

// 用户表单
const userForm = reactive({
  id: undefined,
  nickname: "",
  password: "",
  confirmPassword: "",
  phone: "",
  idCard: "",
  role: "",
  status: 3,
  realName: "",
  address: "",
  remark: "",
});

// 表单验证规则
const userRules = ref({
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 50, message: '昵称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 255, message: '密码长度在 6 到 255 个字符', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 255, message: '真实姓名长度在 2 到 255 个字符', trigger: 'blur' }
  ],
  address: [
    { max: 255, message: '地址长度不能超过 255 个字符', trigger: 'blur' }
  ],
  remark: [
    { max: 255, message: '备注长度不能超过 255 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== userForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
});

// 角色选项
const roleOptions = ref([
  { label: "超级管理员", value: "ROOT" },
  { label: "系统管理员", value: "ADMIN" },
  { label: "普通用户", value: "USER" },
]);

// 计算属性
const dialogTitle = computed(() => (isEdit.value ? "编辑用户" : "新增用户"));

// 引用
const queryFormRef = ref();
const userFormRef = ref();

// 用户数据类型
interface UserItem {
  id?: number;
  nickname?: string;
  password?: string;
  phone?: string;
  idCard?: string;
  role?: string;
  status?: number;
  created_at?: string;
  updated_at?: string;
  realName?: string;
  address?: string;
  remark?: string;
}

// 查询用户列表
const getUserList = async () => {
  loading.value = true;
  let res: any = await UserAPI.userList(queryParams);
  userList.value = res.data;
  total.value = res.pagination.total;
  loading.value = false;
};

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1;
  getUserList();
};

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 刷新
const handleRefresh = () => {
  getUserList();
};

// 新增用户
const handleAdd = () => {
  isEdit.value = false;
  dialogVisible.value = true;
  resetUserForm();
};

// 编辑用户
const handleEdit = (row: UserItem) => {
  isEdit.value = true;
  dialogVisible.value = true;
  Object.assign(userForm, {
    id: row.id,
    nickname: row.nickname,
    phone: row.phone,
    idCard: row.idCard,
    role: row.role,
    status: row.status,
    realName: row.realName,
    address: row.address,
    remark: row.remark,
  });
};

// 删除用户
const handleDelete = async (row: UserItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.realName}" 吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    ).then(async () => {
      let res: any = await UserAPI.deleteUser({ id: row.id })
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getUserList();
      } else {
        ElMessage.error(res.msg);
      }
    });
  } catch (error) {
    // 用户取消删除
  }
};

// 状态切换
const handleStatusChange = async (row: UserItem) => {
  try {
    // 模拟状态更新API调用
    await new Promise((resolve) => setTimeout(resolve, 300));

    ElMessage.success(`${row.status ? "启用" : "禁用"}成功`);
  } catch (error) {
    // 恢复原状态
    row.status = row.status ? 0 : 1;
    ElMessage.error("状态更新失败");
  }
};

// 导出
const handleExport = () => {
  ElMessage.info("导出功能开发中...");
};

// 表格选择变化
const handleSelectionChange = (selection: UserItem[]) => {
  multipleSelection.value = selection;
};

// 提交表单
const handleSubmit = async () => {
  try {
    await userFormRef.value?.validate();
    let res: any;
    if (isEdit.value) {
      res = await UserAPI.updateUser(userForm);
    } else {
      res = await UserAPI.addUser(userForm);
    }
    if (res.code === 200) {
      ElMessage.success(isEdit.value ? "更新成功" : "新增成功");
      dialogVisible.value = false;
      getUserList();
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    submitLoading.value = false;
  }
};

// 对话框关闭
const handleDialogClose = () => {
  userFormRef.value?.resetFields();
  resetUserForm();
};

// 重置用户表单
const resetUserForm = () => {
  Object.assign(userForm, {
    id: undefined,
    nickname: "",
    password: "",
    confirmPassword: "",
    phone: "",
    idCard: "",
    role: "",
    status: 1,
    realName: "",
    address: "",
    remark: "",
  });
};

// 页面加载时获取数据
onMounted(() => {
  getUserList();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .toolbar-left,
  .toolbar-right {
    display: flex;
    gap: 10px;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

// 表格样式优化
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;

  .el-table__header {
    background-color: #f8f9fa;
  }
}

// 头像样式
:deep(.el-avatar) {
  border: 2px solid #e1e8ed;
}

// 状态开关样式
:deep(.el-switch) {
  --el-switch-on-color: #13ce66;
  --el-switch-off-color: #ff4949;
}

// 标签样式
:deep(.el-tag) {
  border-radius: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 10px;

    .toolbar-left,
    .toolbar-right {
      width: 100%;
      justify-content: center;
    }
  }

  .search-container {
    :deep(.el-form--inline) {
      .el-form-item {
        display: block;
        margin-bottom: 10px;

        .el-form-item__content {
          margin-left: 0 !important;
        }
      }
    }
  }
}
</style>
